<?php
/*
 * @Author: zuoyi
 * @Date: 2022-04-16 16:28:56
 * @Copyright: Copyright (c) 2013 - 2022, Iqi, Inc.
 * @Description: 公用列表、添加、编辑、删除
 * 重用代码
 * Traits 是一种在 PHP 等单继承语言中重用代码的机制。Trait 旨在通过使开发人员能够在生活在不同类层次结构中的几个独立类中自由地重用方法集来减少单继承的一些限制。Traits 和类组合的语义以降低复杂性的方式定义，并避免与多继承和 Mixins 相关的典型问题。
 *Trait 类似于类，但仅旨在以细粒度和一致的方式对功能进行分组。无法单独实例化 Trait。它是对传统继承的补充，可以实现行为的横向组合；即类成员的应用不需要继承。
 * @LastEditors: Do not edit
 * @LastEditTime: 2022-05-04 16:17:12
 */
namespace Modules\Common\Library\traits;

use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Modules\Common\Exceptions\CodeData;
use Modules\Common\Exceptions\StatusData;
use Modules\Common\Exceptions\MessageData;
use Modules\Common\Exceptions\ApiException;

trait Commonend
{
    
    /**
     * 排除前台提交过来的字段
     * @param $params
     * @return array
     */
    protected function preExcludeFields($params)
    {
        if (is_array($this->excludeFields)) {
            foreach ($this->excludeFields as $field) {
                if (key_exists($field, $params)) {
                    unset($params[$field]);
                }
            }
        } else {
            if (key_exists($this->excludeFields, $params)) {
                unset($params[$this->excludeFields]);
            }
        }
        return $params;
    }

    // public function index()
    // {
    //     # code...
    // }

    public function recyclebin()
    {
        # code...
    }

    /**
     * @description: 公共添加
     * @param {object} $model 模型
     * @param {array} $data 数据
     * @param {string} $successMessage 成功返回数据
     * @param {string} $errorMessage 失败返回数据
     * @return {json}
     * @Author: zuoyi
     * @Date: 2022-04-16 17:46:36
     * @LastEditTime: Do not edit
     */    
    public function add($model, array $data = [], string $successMessage = MessageData::ADD_API_SUCCESS, string $errorMessage = MessageData::ADD_API_ERROR)
    {
        $data['created_at'] = date('Y-m-d H:i:s');

        $result = false;
        DB::beginTransaction();
        try {
            $result = $model->insert($data);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->apiError($e->getMessage());
        }

        if ($result !== false) {
            return $this->apiSuccess($successMessage);
        } else {
            return $this->apiError($errorMessage);
        }
    }

    /**
     * @description: 公共编辑
     * @param {object} $model 模型
     * @param {int} $id 信息ID
     * @param {array} $data 数据
     * @param {string} $successMessage 成功返回数据
     * @param {string} $errorMessage 失败返回数据
     * @return {json}
     * @Author: zuoyi
     * @Date: 2022-04-16 17:48:22
     * @LastEditTime: Do not edit
     */    
    public function edit($model, int $id, array $data = [], string $successMessage = MessageData::UPDATE_API_SUCCESS, string $errorMessage = MessageData::UPDATE_API_ERROR)
    {
        $data['updated_at'] = date('Y-m-d H:i:s');

        $result = false;
        DB::beginTransaction();
        try {
            $result = $model->where('id', $id)->update($data);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->apiError($e->getMessage());
        }

        if ($result !== false) {
            return $this->apiSuccess($successMessage);
        } else {
            return $this->apiError($errorMessage);
        }
    }

    /**
     * @description: 公共删除（真删除）
     * @param {object} $model 模型
     * @param {string} $ids 信息 多个以英文逗号隔开
     * @param {string} $successMessage 成功返回数据
     * @param {string} $errorMessage 失败返回数据
     * @return {json}
     * @Author: zuoyi
     * @Date: 2022-04-17 10:06:27
     * @LastEditTime: Do not edit
     */    
    public function del($model, $ids, string $successMessage = MessageData::DELETE_API_SUCCESS, string $errorMessage = MessageData::DELETE_API_ERROR)
    {
        if (!empty($ids)) {
            $ids = (array)array_values(explode(',', $ids));
            $list = $model->whereIn('id', $ids)->get();

            $count = 0;
            DB::beginTransaction();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return $this->apiError($e->getMessage());
            }

            if ($count) {
                return $this->apiSuccess($successMessage);
            } else {
                return $this->apiError($errorMessage);
            }
        }
        return $this->apiError($errorMessage);
    }

    /**
     * @description: 公共软删除
     * @param {object} $model 模型
     * @param {string} $ids 信息 多个以英文逗号
     * @param {string} $successMessage 成功返回
     * @param {string} $errorMessage 失败返回数
     * @return {json}
     * @Author: zuoyi
     * @Date: 2022-04-17 11:34:03
     * @LastEditTime: Do not edit
     */    
    public function destroy(
        $model,
        $ids,
        string $successMessage = MessageData::DELETE_API_SUCCESS,
        string $errorMessage = MessageData::DELETE_API_ERROR
    )
    {
        if (!empty($ids)) {
            $ids = (array)array_values(explode(',', $ids));
            $list = $model->whereIn('id', $ids)->get();

            $count = 0;
            DB::beginTransaction();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->update(['is_delete' => 1, 'deleted_at' => date('Y-m-d H:i:s')]);
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return $this->apiError($e->getMessage());
            }
    
            if ($count) {
                return $this->apiSuccess($successMessage);
            } else {
                return $this->apiError($errorMessage);
            }
        }
        return $this->apiError($errorMessage);
    }

    /**
     * @description: 公共软删除恢复
     * @param {object} $model 模型
     * @param {string} $ids 信息 多个以英文逗号
     * @param {string} $successMessage 成功返回
     * @param {string} $errorMessage 失败返回数
     * @return {json}
     * @Author: zuoyi
     * @Date: 2022-04-17 11:34:03
     * @LastEditTime: Do not edit
     */
    public function restore($model, $ids,
        string $successMessage = MessageData::DELETE_RECYCLE_API_SUCCESS,
        string $errorMessage = MessageData::DELETE_RECYCLE_API_ERROR
    )
    {
        if (!empty($ids)) {
            $ids = (array)array_values(explode(',', $ids));
            $list = $model->whereIn('id', $ids)->get();

            $count = 0;
            DB::beginTransaction();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->update(['is_delete' => 0, 'deleted_at' => date('Y-m-d H:i:s')]);
                }
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return $this->apiError($e->getMessage());
            }
    
            if ($count) {
                return $this->apiSuccess($successMessage);
            } else {
                return $this->apiError($errorMessage);
            }
        }
        return $this->apiError($errorMessage);
    }

    /**
     * @description: 公共列表
     * @param {object} $model 模型
     * @param {array} $data 查询信息
     * @param {string} $successMessage 成功返回
     * @param {string} $errorMessage 失败返回数
     * @return {json}
     * @Author: zuoyi
     * @Date: 2022-04-17 11:34:03
     * @LastEditTime: Do not edit
     */
    public function list($model, array $data)
    {
        $where = [];
        $data['order'] = isset($data['order']) && !empty($data['order']) ? $data['order'] : 'id';
        $data['sort'] = isset($data['sort']) && !empty($data['sort']) ? $data['sort'] : 'desc';
        $data['limit'] = isset($data['limit']) && !empty($data['limit']) ? $data['limit'] : 10;
        $list = $model
            ->where($where)
            ->orderBy($data['order'], $data['sort'])
            ->paginate($data['limit'])
            ->toArray();
        return $this->apiSuccess('', [
            'list' => $list['data'],
            'total' => $list['total']
        ]);
    }

    /**
     * @description: 公共详情
     * @param {object} $model 模型
     * @param {string} $ids 信息id
     * @param {string} $successMessage 成功返回
     * @param {string} $errorMessage 失败返回数
     * @return {json}
     * @Author: zuoyi
     * @Date: 2022-04-17 11:34:03
     * @LastEditTime: Do not edit
     */
    public function detail(
        $model,
        int $id,
        string $successMessage = MessageData::DELETE_API_SUCCESS,
        string $errorMessage = MessageData::DELETE_API_ERROR
    )
    {
        if (!empty($id)) {
            $res = $model->find($id);
            if (!empty($res)) {
                return $this->apiSuccess('', $res->toArray());
            } else {
                return $this->apiError($errorMessage);
            }
        }
        return $this->apiError($errorMessage);
    }

    public function multi()
    {
        # code...
    }
    
    public function import()
    {
        # code...
    }
}